package com.fairy.sso.controller;

import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.fairy.core.util.UUIDUtil;
import com.fairy.sso.annotation.FairyControllerExceptionLog;
import com.fairy.sso.config.FairyConfig;
import com.fairy.sso.core.Captcha;
import com.fairy.sso.core.SSOConstants;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

@Controller
public class SSOController {

	private static Logger log = Logger.getLogger(SSOController.class);
	@Autowired(required=true)
	private FairyConfig fairyConfig;
	@RequestMapping ("/index.do")
	public ModelAndView index(HttpServletRequest request,Model model,String service)
	{
		model.addAttribute("service", service);
		String url=fairyConfig.getIndexPageName();
	    ModelAndView mav = new ModelAndView(url);

	    log.info("==========内管登录统一入口"+service+"内管登录统一入口,"+url+"=========");
	    return mav; 
	}
	
	@RequestMapping ("/img.do")
	@FairyControllerExceptionLog(description="获取ticket")
	public void img(HttpServletRequest request, HttpServletResponse response,Model model,RedirectAttributes attr,String ticket)
	{
		response.setContentType("image/jpeg");  
        //禁止图像缓存。  
        response.setHeader("Pragma", "no-cache");  
        response.setHeader("Cache-Control", "no-cache");  
        response.setDateHeader("Expires", 0);  
          
        HttpSession session = request.getSession();  
        
        Captcha c=new Captcha();
        String codes=UUIDUtil.getRandom(4);
        c.generate(120,35, codes);
  
        
        log.info("生成的验证码:"+codes);
        session.setAttribute(SSOConstants.SSO_IMG_CODE, codes); 
     // 禁止图像缓存。  
        response.setHeader("Pragma", "no-cache");  
        response.setHeader("Cache-Control", "no-cache");  
        response.setDateHeader("Expires", 0);  
        response.setContentType("image/jpeg");  
  
        // 将图像输出到Servlet输出流中。  
        ServletOutputStream sos;
		try {
			sos = response.getOutputStream();
	        ImageIO.write(c.getImage(), "jpeg", sos);  
	        sos.close();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}  
  
        /**
        
        try {
            ValidateCode vCode = new ValidateCode(120,40,4,100);  
            String code=vCode.getCode();
            session.setAttribute(SSOConstants.SSO_IMG_CODE, code); 
            log.info("生成的验证码:"+code);
			vCode.write(response.getOutputStream());
		} catch (IOException e) {

			e.printStackTrace();
		}  
        */
	}
	@RequestMapping ("/getDomainList.do")
	@FairyControllerExceptionLog(description="获取跨域域名或者cookie清单")
	public void getDomainList(HttpServletRequest request, HttpServletResponse response,Model model,RedirectAttributes attr,String ticket,String callback)
	{
		//返回头部设置  
		response.setHeader("Pragma", "No-cache");  
		response.setHeader("Cache-Control", "no-cache"); 
		response.setHeader("Content-type", "application/x-javascript;charset=utf-8");
		response.setDateHeader("Expires", 0);  
		response.setContentType("text/plain");
		//response.addHeader("Access-Control-Allow-Origin","*");
		Writer w = null;
		try 
		{
			Map<String,Object>map=new HashMap<>();
			map.put("code", "111111");
			map.put("msg", "失败");
			String st=fairyConfig.getSsoCrossDomainClientAppUrl();
			List<String>list=new ArrayList<>();
			if(null!=st)
			{
				
				if(st.contains(","))
				{
					String []arr=st.split(",");
					for(String str:arr)
					{
						list.add(str);
					}
				}
				else
				{
					list.add(st);
				}
				
			}
			map.put("code", "000000");
			map.put("msg", "成功");
			map.put("list", list);
			

			ObjectMapper mapper = new ObjectMapper();  
		    String json="";
			try {
				json = mapper.writeValueAsString(map);
			} catch (JsonProcessingException e) {
				e.printStackTrace();
			}
			
			w = response.getWriter();
			w.write(callback+"("+json+")");

			w.flush();
			w.close();
		} 
		catch (IOException e) 
		{
			e.printStackTrace();
		}

	}
}
